package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pojo.SysResource;
import com.example.mapper.SysResourceMapper;
import com.example.pojo.SysRoleResource;
import com.example.service.ISysResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.service.ISysRoleResourceService;
import org.omg.CORBA.BAD_QOS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyj
 * @since 2023-02-16
 */
@Service
public class SysResourceServiceImpl extends ServiceImpl<SysResourceMapper, SysResource> implements ISysResourceService {
    @Autowired
    private ISysRoleResourceService sysRoleResourceService;

    @Override
    public List<SysResource> queryByUserId(Long id) {
        QueryWrapper<SysResource> wrapper = new QueryWrapper<>();
        wrapper.apply("su.del_flag=0\n" +
                "and sur.del_flag=0\n" +
                "and srr.del_flag=0\n" +
                "and sre.del_flag=0 ")
                .eq("su.id",id)
                .orderByAsc("sre.sort");
        return baseMapper.queryByUserId(wrapper);
    }

    /**
     * 分配权限
     * @param roleId
     * @param permissions
     * @return
     */
    @Override
    @Transactional
    public boolean assignPermissions(Serializable roleId, List permissions) {
        //根据roleId删除角色权限表关联记录
        boolean remove = sysRoleResourceService.lambdaUpdate().eq(SysRoleResource::getRoleId, roleId).remove();

        //构造角色权限集合并重新插入
        List<SysRoleResource> list = new ArrayList<>();
        for (Object permission : permissions) {
            SysRoleResource sysRoleResource = new SysRoleResource();
            sysRoleResource.setRoleId(Long.parseLong(roleId.toString()));
            sysRoleResource.setResourceId(Long.parseLong(permission.toString()));
            list.add(sysRoleResource);
        }

        //批量插入
        boolean saveBatch = sysRoleResourceService.saveBatch(list);
        return saveBatch;
    }
}
